package com.zhiwei.gateway.controller;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhiwei.common.constant.ErrorEnum;
import com.zhiwei.common.constant.ResultResponseMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义error错误页面
 * <p>
 * 异常处理器: 默认SendErrorFilter
 * 默认错误器： BasicErrorController#error
 * 注意： 404 不走过滤器
 *
 * @author zhiguang
 */
@RestController
@Slf4j
public class ErrorHandlerController implements ErrorController {

    /**
     * 出异常后进入该方法，交由下面的方法处理
     */
    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    public ResultResponseMsg error(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        int statusCode = httpServletResponse.getStatus();
        String originUri = String.valueOf(httpServletRequest.getAttribute("javax.servlet.forward.request_uri"));
        String targetUri = String.valueOf(httpServletRequest.getAttribute("javax.servlet.forward.servlet_path"));
        //404
        if (HttpStatus.NOT_FOUND.value() == statusCode) {
            log.info("请求服务接口【{}】==>【{}】不存在", originUri, targetUri);
            return ResultResponseMsg.buildResultMsg(ErrorEnum.SERVICE_REMOTE, null);
        } else {
            RequestContext ctx = RequestContext.getCurrentContext();
            ZuulException zuulException = (ZuulException) ctx.getThrowable();
            log.info("请求服务接口【{}】==>【{}】异常", originUri, targetUri, zuulException);
            return ResultResponseMsg.buildFailureResultMsg(zuulException.getMessage());
        }
    }
}